﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;

namespace Sofire.Data.XSql
{
    /*
     * 1、缓存机制需要斟酌
     * 2、需增加公共表达式
     * 3、性能测试
     */
    internal class XSqlCacheHelper
    {
        public static int GetNamesKey(XSqlParameterCollection parameters)
        {
            int hashCode = parameters.Count;
            foreach(var item in parameters)
            {
                hashCode ^= item.Name.GetHashCode();
            }
            return hashCode;
        }

        public static int GetValuesKey(XSqlParameterCollection parameters)
        {
            int hashCode = parameters.Count;
            foreach(var item in parameters)
            {
                hashCode ^= item.Name.GetHashCode() ^ BuilderHashCode(item.Value);
            }
            return hashCode;
        }

        private static readonly int NullHashCode = DBNull.Value.GetHashCode();
        private static int BuilderHashCode(object value)
        {
            if(value == null || Convert.IsDBNull(value)) return NullHashCode;
            if(value is string
                || value is int
                || value is double
                || value is decimal) return value.GetHashCode();

            var e = value as IEnumerable;
            if(e != null)
            {
                int count;
                if(e is ICollection) count = (e as ICollection).Count;
                else if(e is Array) count = (e as Array).Length;
                else
                {
                    count = 0;
                    foreach(var item in e)
                    {
                        count++;
                    }
                }

                foreach(var item in e)
                {
                    count ^= BuilderHashCode(item);
                }
                return count;
            }

            return value.GetHashCode();

        }
    }
}
